#include "TabSettings.h"
#include "OpenaiManager.h"
#include <QCoreApplication>
#include <QFileDialog>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QMessageBox>
#include <QSettings>
#include <QSysInfo>
#include <QTimer>
#include <QVBoxLayout>

SettingsTab::SettingsTab(QWidget *parent)
    : QWidget(parent), m_checkServerTimer(nullptr), m_llamaServer(new LlamaServerManager(this)),
      m_logOutput(nullptr)
{
    createUI();
    setDefaultValues();
    useLatestHistory();
}

void SettingsTab::createUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // OpenAI设置区域
    QGroupBox *apiGroup    = new QGroupBox("OpenAI设置", this);
    QGridLayout *apiLayout = new QGridLayout(apiGroup);

    m_apiKeyEdit = new QLineEdit(this);
    m_apiKeyEdit->setPlaceholderText("API Key");
    m_urlEdit    = new QLineEdit(this);
    m_modelEdit  = new QLineEdit(this);
    m_testButton = new QPushButton("测试连接", this);
    m_testResult = new QLineEdit(this);
    m_testResult->setReadOnly(true);

    m_historyCombo = new QComboBox(this);
    m_historyCombo->addItem("择历史记录...");
    apiLayout->addWidget(new QLabel("历史记录:", this), 0, 0);
    apiLayout->addWidget(m_historyCombo, 0, 1);

    apiLayout->addWidget(new QLabel("API Key:", this), 1, 0);
    apiLayout->addWidget(m_apiKeyEdit, 1, 1);
    apiLayout->addWidget(new QLabel("URL:", this), 2, 0);
    apiLayout->addWidget(m_urlEdit, 2, 1);
    apiLayout->addWidget(new QLabel("Model:", this), 3, 0);
    apiLayout->addWidget(m_modelEdit, 3, 1);
    apiLayout->addWidget(m_testButton, 4, 0);
    apiLayout->addWidget(m_testResult, 4, 1);

    mainLayout->addWidget(apiGroup);

    // 连接历史记录选择信号
    connect(m_historyCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
            &SettingsTab::onHistorySelected);

    // 本地AI服务设置区域
    QGroupBox *localAIGroup    = new QGroupBox("本地AI服务设置", this);
    QGridLayout *localAILayout = new QGridLayout(localAIGroup);

    m_useLocalAICheck = new QCheckBox("使用本地AI服务", this);
    m_modelPathEdit   = new QLineEdit(this);
    m_modelPathEdit->setPlaceholderText("AI模型文件路径");
    m_selectModelButton = new QPushButton("选择模型", this);
    m_hostEdit          = new QLineEdit(this);
    m_portEdit          = new QLineEdit(this);
    m_tempEdit          = new QLineEdit(this);
    m_contextSizeEdit   = new QLineEdit(this);
    m_nglEdit           = new QLineEdit(this);

    localAILayout->addWidget(m_useLocalAICheck, 0, 0, 1, 2);
    localAILayout->addWidget(new QLabel("模型路径:", this), 1, 0);
    QHBoxLayout *modelPathLayout = new QHBoxLayout();
    modelPathLayout->addWidget(m_modelPathEdit);
    modelPathLayout->addWidget(m_selectModelButton);
    localAILayout->addLayout(modelPathLayout, 1, 1);
    localAILayout->addWidget(new QLabel("主机地址:", this), 2, 0);
    localAILayout->addWidget(m_hostEdit, 2, 1);
    localAILayout->addWidget(new QLabel("端口:", this), 3, 0);
    localAILayout->addWidget(m_portEdit, 3, 1);
    localAILayout->addWidget(new QLabel("温度:", this), 4, 0);
    localAILayout->addWidget(m_tempEdit, 4, 1);
    localAILayout->addWidget(new QLabel("上下文大小:", this), 5, 0);
    localAILayout->addWidget(m_contextSizeEdit, 5, 1);
    localAILayout->addWidget(new QLabel("NGL:", this), 6, 0);
    localAILayout->addWidget(m_nglEdit, 6, 1);

    mainLayout->addWidget(localAIGroup);

    // 添加恢复默认设置按钮
    m_resetButton = new QPushButton("恢复默认设置", this);
    mainLayout->addWidget(m_resetButton);

    // 连接信号槽
    connect(m_useLocalAICheck, &QCheckBox::toggled, this, &SettingsTab::onLocalAIToggled);
    connect(m_selectModelButton, &QPushButton::clicked, this, &SettingsTab::selectModelFile);
    connect(m_testButton, &QPushButton::clicked, this, &SettingsTab::testApiConnection);
    connect(m_resetButton, &QPushButton::clicked, this,
            [this]()
            {
                if (QMessageBox::question(this, "确认", "确定要恢复默认设置吗？") ==
                    QMessageBox::Yes)
                {
                    setDefaultValues();
                    emit logMessage("已恢复默认设置");
                }
            });

    mainLayout->addStretch();
}

void SettingsTab::setDefaultValues()
{
    // 只设置默认值
    m_urlEdit->setText("http://127.0.0.1:11434/v1/chat/completions");
    m_apiKeyEdit->setText("123456");
    m_modelEdit->setText("qwen2.5:3b-instruct-q8_0");
    
    // 本地AI服务的默认值
    m_useLocalAICheck->setChecked(false);
    m_modelPathEdit->setText(QCoreApplication::applicationDirPath() + "/model/model.GGUF");
    m_hostEdit->setText("127.0.0.1");
    m_portEdit->setText("11434");
    m_tempEdit->setText("0.7");
    m_contextSizeEdit->setText("2048");
    m_nglEdit->setText("100");
    
    emit logMessage("已恢复默认OpenAI设置");
}

void SettingsTab::useLatestHistory()
{
    if (!m_historySettings.isEmpty()) {
        const OpenAISettings& latest = m_historySettings.first();
        m_urlEdit->setText(latest.url);
        m_apiKeyEdit->setText(latest.apiKey);
        m_modelEdit->setText(latest.model);
        emit logMessage("使用最近的历史OpenAI设置");
    } else {
        // 如果没有历史记录，则使用默认值
        setDefaultValues();
    }
}

void SettingsTab::loadSettings(const QString &settingsPath)
{
    // 使用正确的配置文件路径
    QSettings openaiSettings(QCoreApplication::applicationDirPath() + "/openai_config.ini", QSettings::IniFormat);
    QSettings localAISettings(QCoreApplication::applicationDirPath() + "/local_ai_config.ini", QSettings::IniFormat);

    // 加载OpenAI历史记录
    m_historySettings.clear();
    m_historyCombo->clear();
    m_historyCombo->addItem("选择历史记录...");

    openaiSettings.beginGroup("OpenAIHistory");
    int size = openaiSettings.value("size", 0).toInt();
    emit logMessage("读取到OpenAI历史记录数量：" + QString::number(size));

    for (int i = 1; i <= size; ++i) {
        OpenAISettings hist;
        QString prefix = QString::number(i);
        
        // 读取历史记录
        hist.apiKey = openaiSettings.value(prefix + "/apiKey").toString();
        hist.url = openaiSettings.value(prefix + "/url").toString();
        hist.model = openaiSettings.value(prefix + "/model").toString();
        
        // 只添加非空的记录
        if (!hist.apiKey.isEmpty() && !hist.url.isEmpty() && !hist.model.isEmpty()) {
            m_historySettings.append(hist);
            m_historyCombo->addItem(QString("%1 (%2)").arg(hist.model).arg(hist.url));
        }
    }
    openaiSettings.endGroup();

    // 使用最新的历史记录，如果没有则使用默认值
    useLatestHistory();

    // 加载本地AI服务设置
    localAISettings.beginGroup("LocalAI");
    
    // m_useLocalAICheck始终默认为关闭状态，不从配置文件加载
    m_useLocalAICheck->setChecked(false);
    
    // 加载其他本地AI服务设置
    m_modelPathEdit->setText(localAISettings.value("modelPath", 
        QCoreApplication::applicationDirPath() + "/model/model.GGUF").toString());
    m_hostEdit->setText(localAISettings.value("host", "127.0.0.1").toString());
    m_portEdit->setText(localAISettings.value("port", "11434").toString());
    m_tempEdit->setText(localAISettings.value("temp", "0.7").toString());
    m_contextSizeEdit->setText(localAISettings.value("contextSize", "2048").toString());
    m_nglEdit->setText(localAISettings.value("ngl", "100").toString());

    localAISettings.endGroup();

    emit logMessage("本地AI服务设置加载完成");
}

void SettingsTab::saveSettings(const QString &settingsPath)
{
    // OpenAI设置保存到单独的配置文件
    QSettings openaiSettings(QCoreApplication::applicationDirPath() + "/openai_config.ini", 
        QSettings::IniFormat);
    
    openaiSettings.beginGroup("OpenAI");
    openaiSettings.setValue("url", m_urlEdit->text());
    openaiSettings.setValue("apiKey", m_apiKeyEdit->text());
    openaiSettings.setValue("model", m_modelEdit->text());
    openaiSettings.endGroup();
    
    openaiSettings.sync();

    // 本地AI服务设置保存到单独的配置文件
    QSettings localAISettings(QCoreApplication::applicationDirPath() + "/local_ai_config.ini", 
        QSettings::IniFormat);
    
    localAISettings.beginGroup("LocalAI");
    
    // 保存其他本地AI服务设置
    localAISettings.setValue("modelPath", m_modelPathEdit->text());
    localAISettings.setValue("host", m_hostEdit->text());
    localAISettings.setValue("port", m_portEdit->text());
    localAISettings.setValue("temp", m_tempEdit->text());
    localAISettings.setValue("contextSize", m_contextSizeEdit->text());
    localAISettings.setValue("ngl", m_nglEdit->text());
    localAISettings.endGroup();
    
    localAISettings.sync();

    emit logMessage("OpenAI设置和本地AI服务设置已分别保存到独立配置文件");
}

void SettingsTab::onLocalAIToggled(bool checked)
{
    if (checked)
    {
        QString programPath;
        if (QSysInfo::productType() == "windows")
        {
            programPath = QCoreApplication::applicationDirPath() + "/llama_bin/llama-server.exe";
        }
        else
        {
            programPath = QCoreApplication::applicationDirPath() + "/llama_bin/llama-server";
        }

        bool success = m_llamaServer->startServer(
            programPath, m_modelPathEdit->text(), m_hostEdit->text(), m_portEdit->text(),
            m_tempEdit->text(), m_contextSizeEdit->text(), m_nglEdit->text());

        if (!success)
        {
            emit logMessage("本地AI服务启动失败");
            QMessageBox::critical(this, "错误", "本地AI服务启动失败，请检查设置和程序路径");
            m_useLocalAICheck->setChecked(false);
            return;
        }

        if (m_checkServerTimer)
        {
            delete m_checkServerTimer;
        }
        m_checkServerTimer = new QTimer(this);
        m_checkServerTimer->setSingleShot(true);
        connect(m_checkServerTimer, &QTimer::timeout, this,
                [this]()
                {
                    if (!m_llamaServer->isRunning())
                    {
                        emit logMessage("本地AI服务启动错误");
                        QMessageBox::critical(this, "错误",
                                              "本地AI服务启动错误，请检查设置和程序路径");
                        m_useLocalAICheck->setChecked(false);
                        m_llamaServer->stopServer();
                    }
                    else
                    {
                        emit logMessage("本地AI服务已成功启动并运行");
                        QMessageBox::information(this, "成功", "本地AI服务已启动");
                    }
                });

        emit logMessage("本地AI服务正在启动请稍等...");

        m_checkServerTimer->start(3000);
    }
    else
    {
        m_llamaServer->stopServer();
        emit logMessage("本地AI服务已停止");
    }
}

void SettingsTab::selectModelFile()
{
    QString filePath = QFileDialog::getOpenFileName(this, "选择AI模型文件", m_modelPathEdit->text(),
                                                    "GGUF模型文件 (*.gguf);;所有文件 (*.*)");

    if (!filePath.isEmpty())
    {
        m_modelPathEdit->setText(filePath);
        emit logMessage("已选择模型文件: " + filePath);
    }
}

void SettingsTab::testApiConnection()
{
    QString apiKey = m_apiKeyEdit->text();
    QString url    = m_urlEdit->text();
    QString model  = m_modelEdit->text();

    emit logMessage("正在测试API连接...");

    m_testResult->setText("正在测试API连接...");
    m_testResult->setStyleSheet("color: black;");

    OpenaiManager *manager = OpenaiManager::getInstance();
    bool success           = manager->testApi(url, apiKey, model);

    if (success)
    {
        m_testResult->setText("连接成功");
        m_testResult->setStyleSheet("color: green;");
        emit logMessage("API连接测试成功");
        const_cast<SettingsTab *>(this)->saveToHistory();
    }
    else
    {
        m_testResult->setText("连接失败");
        m_testResult->setStyleSheet("color: red;");
        emit logMessage("API连接测试失败");
    }
}

void SettingsTab::saveToHistory()
{
    // 获取当前设置
    OpenAISettings current;
    current.apiKey = m_apiKeyEdit->text().trimmed();
    current.url = m_urlEdit->text().trimmed();
    current.model = m_modelEdit->text().trimmed();

    // 检查是否为空
    if (current.apiKey.isEmpty() || current.url.isEmpty() || current.model.isEmpty()) {
        emit logMessage("当前设置不完整，未保存到历史记录");
        return;
    }

    // 检查是否已存在相同配置
    for (int i = 0; i < m_historySettings.size(); ++i) {
        const auto& settings = m_historySettings[i];
        if (settings.apiKey == current.apiKey && 
            settings.url == current.url && 
            settings.model == current.model) {
            // 如果存在相同配置，将其移到最前面
            if (i > 0) {
                m_historySettings.removeAt(i);
                m_historySettings.prepend(current);
                updateComboBox();
                saveHistoryToSettings();
                emit logMessage("已更新历史记录顺序");
            }
            return;
        }
    }

    // 添加新配置到历史记录
    m_historySettings.prepend(current);

    // 限制历史记录数量
    while (m_historySettings.size() > MAX_HISTORY) {
        m_historySettings.removeLast();
    }

    // 更新界面和保存配置
    updateComboBox();
    saveHistoryToSettings();
    emit logMessage("新设置已添加到历史记录");
}

void SettingsTab::updateComboBox()
{
    m_historyCombo->clear();
    m_historyCombo->addItem("选择历史记录...");
    for (const auto& settings : m_historySettings) {
        m_historyCombo->addItem(QString("%1 (%2)").arg(settings.model).arg(settings.url));
    }
}

void SettingsTab::saveHistoryToSettings()
{
    QSettings settings(QCoreApplication::applicationDirPath() + "/openai_config.ini", QSettings::IniFormat);
    
    // 先清除原有的历史记录
    settings.remove("OpenAIHistory");
    
    // 保存新的历史记录
    settings.beginGroup("OpenAIHistory");
    settings.setValue("size", m_historySettings.size());
    
    for (int i = 0; i < m_historySettings.size(); ++i) {
        QString prefix = QString::number(i + 1);
        settings.setValue(prefix + "/apiKey", m_historySettings[i].apiKey);
        settings.setValue(prefix + "/url", m_historySettings[i].url);
        settings.setValue(prefix + "/model", m_historySettings[i].model);
    }
    settings.endGroup();
    settings.sync();

    emit logMessage("历史记录已保存，数量：" + QString::number(m_historySettings.size()));
}

QString SettingsTab::getApiKey() const
{
    // 只在API测试成功后保存历史记录，不在这里保存
    return m_apiKeyEdit->text().trimmed();
}

QString SettingsTab::getUrl() const
{
    return m_urlEdit->text().trimmed();
}

QString SettingsTab::getModel() const
{
    return m_modelEdit->text().trimmed();
}

void SettingsTab::onHistorySelected(int index)
{
    if (index <= 0 || index > m_historySettings.size()) {
        return;
    }

    const OpenAISettings& selected = m_historySettings[index - 1];
    
    // 检查数据有效性
    if (selected.apiKey.isEmpty() || selected.url.isEmpty() || selected.model.isEmpty()) {
        emit logMessage("历史记录数据无效");
        return;
    }

    m_apiKeyEdit->setText(selected.apiKey);
    m_urlEdit->setText(selected.url);
    m_modelEdit->setText(selected.model);

    emit logMessage(QString("已加载历史OpenAI设置：%1 (%2)").arg(selected.model).arg(selected.url));
}
